package com.demo.multThread;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipInputStream;

public class Client {
    public Socket socket;
    private String ip;
    private int port;

    public Client(String ip, int port) {
        try {
            this.socket = new Socket(ip, port);
            System.out.println("Client向 " + ip + ":" + port + " 发起连接请求");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }

}

class getImg implements Runnable {
    private Socket socket;
    private String ip;
    private int port;
    long s1, e1;
    BorderInit frame = new BorderInit();

    public getImg(String ip, int port) {
        // this.socket = socket;Socket socket,
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void run() {
        while (frame.getFlag()) {
            try {
                socket = new Socket(this.ip, this.port);
                DataInputStream ImgInput = new DataInputStream(socket.getInputStream());

                BufferedInputStream bi = new BufferedInputStream(ImgInput);
                s1 = System.currentTimeMillis();
                Image img = ImageIO.read(bi);
                e1 = System.currentTimeMillis();
                System.out.println("Client Read:" + (e1 - s1));
                frame.jlbImg.setIcon(new ImageIcon(img));
                frame.validate();
                TimeUnit.MILLISECONDS.sleep(50);
                // bi.close();
                socket.shutdownOutput();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class BorderInit extends JFrame {
    private static final long serialVersionUID = 1L;
    public JLabel jlbImg;
    private boolean flag;

    public boolean getFlag() {
        return this.flag;
    }

    public BorderInit() {
        this.flag = true;
        this.jlbImg = new JLabel();
        this.setTitle("屏幕分享");
        this.setSize(800, 800);
        this.add(jlbImg);
        this.setLocationRelativeTo(null);
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);
        this.validate();

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                flag = false;
                BorderInit.this.dispose();
                System.gc();
            }
        });
    }
}
